package com.yao.nettydemo.base;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @author Administrator
 */
public class Server {
    public static void main(String[] args) throws InterruptedException {
        // 创建EventLoopGroup用于接收处理新的客户端连接请求
        EventLoopGroup parent = new NioEventLoopGroup();
        // 创建EventLoopGroup 处理每个连接的事件
        EventLoopGroup child = new NioEventLoopGroup();
        try {
            //创建server
            ServerBootstrap bootstrap = new ServerBootstrap();
            //绑定连接处理group
            bootstrap.group(parent,child)
                    //使用NIO连接
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //每当新的连接，会创建一个channel，并且添加一个serverHandler 处理事件\
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new StringEncoder());
                            ch.pipeline().addLast(new ServerHandler());
                        }
                    });
            //异步绑定服务器，调用sync阻塞直到绑定完成
            ChannelFuture f = bootstrap.bind(8988).sync();
            //获取channel的closeFuture（关闭时返回）
            f.channel().closeFuture().sync();
        } finally {
            parent.shutdownGracefully();
            child.shutdownGracefully();
        }

    }
}
